package com.mrzhou.auth.authorzation.impl;

import com.mrzhou.auth.authorzation.AbstractIntegrationAuthentication;
import com.mrzhou.auth.exception.IntegrationException;
import com.mrzhou.auth.service.CloudUserDetails;
import com.mrzhou.auth.support.IntegrationAuthenticationEntity;
import com.mrzhou.auth.utils.TokenUtil;
import com.mrzhou.common.entity.system.UserInfo;
import com.mrzhou.common.enums.MailPhoneType;
import com.mrzhou.common.feign.client.IUserClient;
import com.mrzhou.core.tool.api.R;
import com.mrzhou.msg.feign.client.IMsgClient;
import com.mrzhou.msg.vo.req.ValidMailPhoneReq;
import com.mrzhou.web.util.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 邮箱或者手机验证码登录
 * @author qiang.zhou
 */
@Component
public class MailPhoneAuthentication extends AbstractIntegrationAuthentication {
    @Autowired
    private IMsgClient msgClient;
    @Autowired
    private IUserClient userClient;

    @Override
    public CloudUserDetails authentication(IntegrationAuthenticationEntity authEntity) throws IntegrationException {
        R<UserInfo> result = userClient.userInfo(authEntity.getUsername());
        if(!result.isSuccess()) {
            throw new IntegrationException(result.getMsg());
        }
        return CloudUserDetails.createCloudUserDetails(result.getData());
    }

    /**
     * 前置处理
     * @param authEntity
     * @throws IntegrationException
     */
    @Override
    public void prepare(IntegrationAuthenticationEntity authEntity) throws IntegrationException {
        // 检查验证码是否输入正确
        R<String> result = msgClient.validMailCode(this.validMailPhoneReqHandler(authEntity));
        if (!result.isSuccess()) {
           throw new IntegrationException(result.getMsg());
        }
    }

    @Override
    public boolean support(IntegrationAuthenticationEntity authEntity) {
        return TokenUtil.AUTH_SMS.equalsIgnoreCase(authEntity.getAuthType());
    }

    /**
     * 组装校验邮箱或者手机验证码参数
     * @param authEntity
     * @return
     */
    private ValidMailPhoneReq validMailPhoneReqHandler(IntegrationAuthenticationEntity authEntity) {
        ValidMailPhoneReq req = new ValidMailPhoneReq();
        req.setMailPhone(authEntity.getAuthParameter(TokenUtil.USERNAME_PARAM));
        req.setCode(authEntity.getAuthParameter(TokenUtil.SMS_CODE_PARAM));
        req.setType(MailPhoneType.LOGIN.code());
        req.setClientIP(WebUtil.getIp());
        return req;
    }

}
